package com.example.springboot.wechat.wechatinterface.util;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class HttpClientUtils {

    /**
     * post方式访问网络资源
     *
     * @param url:网络资源链接
     * @param params     参数
     * @return
     * @Title: post
     * @author ; zhangai
     * @Description : TODO
     * @Date ; 2015-7-15 上午10:04:22
     * @version ; 1.0
     */
    public static String post(String url, Map<String, String> params) {
        // 默认的client类。
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpPost post = postForm(url, params);
        String body = invoke(httpclient, post);
        // 关闭连接. 
        httpclient.getConnectionManager().shutdown();
        return body;
    }

    /**
     * get方式访问网络资源
     *
     * @param url
     * @return
     * @Title: get
     * @author ; zhangai
     * @Description : TODO
     * @Date ; 2015-7-15 上午10:05:34
     * @version ; 1.0
     */
    public static String get(String url) {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        // 设置为get取连接的方式.
        HttpGet get = new HttpGet(url);
        String body = invoke(httpclient, get);
        // 关闭连接.
        httpclient.getConnectionManager().shutdown();
        return body;
    }


    private static String invoke(DefaultHttpClient httpclient,
                                 HttpUriRequest httpost) {
        HttpResponse response = sendRequest(httpclient, httpost);
        String body = paseResponse(response);
        return body;
    }

    private static String paseResponse(HttpResponse response) {
        //获取本地信息
        HttpEntity entity = response.getEntity();
        String charset = EntityUtils.getContentCharSet(entity);
        String body = null;
        try {
            body = EntityUtils.toString(entity);
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return body;
    }

    /**
     * 传递本地的http上下文给服务器
     *
     * @param httpclient
     * @param httpost
     * @return
     * @Title: sendRequest
     * @author ; zhangai
     * @Description : TODO
     * @Date ; 2015-7-15 上午10:25:03
     * @version ; 1.0
     */
    private static HttpResponse sendRequest(DefaultHttpClient httpclient,
                                            HttpUriRequest httpost) {
        HttpResponse response = null;
        try {
            //传递本地的http上下文给服务器
            response = httpclient.execute(httpost);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response;
    }

    private static HttpPost postForm(String url, Map<String, String> params) {
        // 设置为Post取连接的方式.
        HttpPost httpost = new HttpPost(url);
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        Set<String> keySet = params.keySet();
        for (String key : keySet) {
            nvps.add(new BasicNameValuePair(key, params.get(key)));
        }
        try {
            // 设置请求的编码格式
            httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return httpost;
    }


    public static String get(String url, String chartset) {

        if (StringUtils.isEmpty(chartset)) {
            chartset = "UTF-8";
        }
        StringBuffer content = new StringBuffer();
        HttpURLConnection httpConn = null;
        BufferedReader in = null;
        try {
            URL url1 = new URL(url);
            httpConn = (HttpURLConnection) url1.openConnection();
            // 读取响应
            if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                String tempStr = "";
                in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), chartset));
                while ((tempStr = in.readLine()) != null) {
                    content.append(tempStr);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (httpConn != null) {
                httpConn.disconnect();
            }
        }
        return content.toString();
    }
}
